const router = require('koa-router')();
const { sign } = require('../libs/security');
let { clientId, clientSecret, cb_url } = require('../config.js').github;
let User = require('../models/user.js');
let File = require('../models/file.js');
let Address = require('../models/address');
let multer = require('koa-multer');
let mkdirp = require('mkdirp');
let config = require('../config.js');
let fs = require('fs');
let path = require('path');
let Record = require('../models/record.js');
let request = require('../libs/request.js');
let ErrorLog = require('../models/errorLog');
let {sendCode} = require('../libs/mail.js');
let { set, get } = require('../libs/redis.js');
let { ak, ipAk } = require('../config.js').baidu;
let { isPoneAvailable, mailReg } = require('../libs/utils.js');
let currMonth = new Date().toISOString().substr(0, 7);
let dest = `uploads/${currMonth}/`;
let upload = multer({dest: dest});
// eslint-disable-next-line
fs.existsSync(upload) ? '' : mkdirp.sync(path.join(__dirname, '../', dest));

/**
 * 注册
 */
router.post('/signUp', async (ctx, next) => {
  try {
    let { password, email, code } = ctx.request.body;
    if ((!email) || (!password) || !code) {
      throw new Error('缺少参数');
    } else {
      if (email && !mailReg.test(email)) {
        throw new Error('邮箱不合法');
      }
      let _code = await get(email);
      if (!_code) {
        throw new Error('验证码已过期');
      } else if (_code !== +code) {
        throw new Error('验证码错误');
      }
      let u = await User.findOne({
        email
      });
      if (u) {
        throw new Error('用户已经存在');
      } else {
        let pwd = sign(password);
        await User.create({
          password: pwd,
          email
        });
        ctx.success({msg: 'signUp successful!'});
      }
    }
  } catch (err) {
    throw err;
  }
});

/**
 * 登录 后台管理系统
 */
router.post('/signIn', async (ctx, next) => {
  try {
    let {phone, email, password} = ctx.request.body;
    if ((!email) || (!password)) {
      throw new Error('缺少参数');
    } else {
      if (email && !mailReg.test(email)) {
        throw new Error('邮箱格式不正确');
      }
      if (phone && !isPoneAvailable(phone)) {
        throw new Error('手机格式不正确');
      }
    }
    let pwd = sign(password);
    let u = await User.findOne({$or: [
      {
        phone,
        password: pwd,
        status: true
      }, {
        email,
        password: pwd,
        status: true
      }
    ]});
    if (u) {
      if (u._doc.type !== '01') {
        throw new Error('抱歉您没有权限登录当前页面,请联系管理员添加');
      }
      let token = ctx.createToken(u.userId);
      let user = u._doc;
      user.token = token;
      await ctx.setSession(u, token);
      delete user._id;
      delete user.password;
      delete user.updatedAt;
      delete user.createdAt;
      delete user.secret;
      let ip = '';
      if (config.env === 'development') {
        ip = ctx.ip.substr(7, 11);
      } else {
        ip = ctx.header['x-forwarded-for'];
      }
      await Record.create({ip, userId: u.userId, info: 'login-system'});
      let info = await getWeatherInfo(ip, u.userId);
      let weather = Object.assign(info.weather_data[0], {currentCity: info.currentCity});
      delete user.loginAddress;
      ctx.success(Object.assign({}, user, {weather}));
    } else {
      throw new Error('账号不存在');
    }
  } catch (err) {
    throw err;
  }
});
/**
 * 电商登录
 */
router.post('/login', async (ctx, next) => {
  try {
    let { account, password } = ctx.request.body;

    if (!account || !password) {
      throw new Error('缺少参数');
    } else {
      let pwd = sign(password);
      let u = await User.findOne({
        email: account, password: pwd, status: true, $or: [{type: '02'}, {type: '01'}]
      });
      if (u) {
        let ip = '';
        if (config.env === 'development') {
          ip = ctx.ip.substr(7, 11);
        } else {
          ip = ctx.header['x-forwarded-for'];
        }
        await Record.create({ip, userId: u.userId, info: 'login-dianshang'});
        let token = ctx.createToken(u.userId);
        await ctx.setSession(u, token);
        ctx.success({token});
      } else {
        throw new Error('请检查账号和密码');
      }
    }
  } catch (err) {
    throw err;
  }
});
/**
 * 电商注册
 */
router.post('/register', async (ctx, next) => {
  try {
    let { account, password, username } = ctx.request.body;
    if (!account || !password || !username) {
      throw new Error('缺少参数');
    }
    let u = await User.findOne({email: account});
    if (u && u.userId) {
      throw new Error('您的邮箱已被注册');
    } else {
      let pwd = sign(password);
      await User.create({
        email: account,
        password: pwd,
        name: username
      });
      ctx.success({data: '注册成功'});
    }
  } catch (err) {
    throw err;
  }
});

// 退出登录
router.post('/quit', async (ctx, next) => {
  try {
    await ctx.delSession(ctx.req.headers.token);
    ctx.success({msg: 'quit successful'});
  } catch (err) {
    throw err;
  }
});

/**
 *上传文件
 */
router.post('/uploadFile', upload.array('files', 12), async (ctx, next) => {
  try {
    let files = ctx.req.files;
    let f = [];
    for (let i = 0; i < files.length; i++) {
      let item = files[i];
      let ret = await File.create({
        savePath: item.path,
        fileName: item.filename,
        mimeType: item.mimetype,
        size: item.size,
        originalname: item.originalname,
        account: ctx.userId || ''
      });
      f.push({_id: ret._id});
    }
    ctx.success(f);
  } catch (err) {
    throw err;
  }
});

/**
 * 下载文件
 */
router.get('/downLoadFile', async (ctx, next) => {
  try {
    let {fileId} = ctx.query;
    if (fileId === 'default') {
      ctx.res.setHeader('Content-type', 'image/png');
      ctx.body = fs.createReadStream(path.resolve(process.env.dataDir, 'public/default.png'));
    } else {
      let f = await File.findOne({_id: fileId});
      ctx.res.setHeader('Content-disposition', `attachment; filename=${encodeURIComponent(f.originalname)};filename*=utf-8${f.fileName}`);
      ctx.res.setHeader('Content-type', f.mimeType);
      // eslint-disable-next-line
      f.size ? ctx.res.setHeader('Content-Length', Number(+f.size).toString()) : '';
      ctx.body = fs.createReadStream(path.resolve(process.env.dataDir, f.savePath));
    }
  } catch (err) {
    throw err;
  }
});

/**
 * 发送验证码
 */
router.post('/sendCode', async (ctx, next) => {
  try {
    let {to} = ctx.request.body;
    let code = Math.random(16).toString().substring(2, 6);
    await set(to, code, 60 * 5);
    let html = `欢迎注册xxx电影网站,您的注册码:${code},请注意查收`;
    try {
      await sendCode(ctx, to, html);
      ctx.success();
    } catch (error) {
      throw error;
    }
  } catch (err) {
    throw err;
  }
});

let getWeatherInfo = async (ip, userId) => {
  try {
    // 根据ip进行定位
    let getAddress = await request({
      uri: `http://api.map.baidu.com/location/ip`,
      method: 'GET',
      qs: {
        ip,
        ak: ipAk
      },
      json: true
    });
    let address = '深圳';
    if (getAddress && getAddress.content) {
      address = getAddress.content.address_detail.city;
      await Address.create({
        name: getAddress.content.address_detail.city,
        ip,
        userId
      });
    }
    let options = {
      uri: `https://api.map.baidu.com/telematics/v3/weather`,
      method: 'GET',
      qs: {
        location: address,
        output: 'json',
        ak
      },
      json: true
    };
    // 根据城市查天气
    let res = await request(options);
    return res.results[0];
  } catch (err) {
    console.log('22222:', err);
  }
};

router.get('/github', async (ctx, next) => {
  try {
    let url = `http://github.com/login/oauth/authorize?client_id=${clientId}&scope=user:email`;
    ctx.redirect(url);
  } catch (err) {
    throw err;
  }
});
/**
 * github 回调地址
 */
router.get('/git_cb', async (ctx, next) => {
  try {
    // clientId, clientSecret
    let { code } = ctx.query;
    console.log('git_cb:', ctx.query);
    let options = {
      uri: `https://github.com/login/oauth/access_token`,
      qs: {
        client_id: clientId,
        client_secret: clientSecret,
        code
      },
      json: true
    };
    let res = await request(options);
    console.log('xxxxxxxx:', res);
    let options1 = {
      uri: `https://api.github.com/user`,
      qs: {
        access_token: res.access_token
      },
      json: true
    };
    console.log('yyyyyyy:', options1);
    let res1 = await request(options1);
    console.log('111111:', res1);
    ctx.redirect('http://film.ishareu.cn/');
    // await getUser(res.access_token);
  } catch (err) {
    throw err;
  }
});
/**
 *
 * 从github获取用户信息
 */
let getUser = async (token) => {
  try {
    let options = {
      uri: `https://api.github.com/user`,
      qs: {
        access_token: token
      },
      json: true
    };
    console.log('yyyyyyy:', options);
    let res = await request(options);
    console.log('111111:', res);
  } catch (err) {
    throw err;
  }
};

/**
 * 收集前端的错误日志
 * @type {[type]}
 */
router.get('/errorLog', async (ctx, next) => {
  try {
    let { err, info, url, platform } = ctx.query;
    await ErrorLog.create({err, info, url, platform});
    ctx.success(`successful`);
  } catch (err) {
    throw err;
  }
});

module.exports = router;
